package com.apkplug.test;

import android.app.Application;
import android.util.Log;

import com.apkplug.test.lib.LoginManager;

import org.apkplug.Bundle.InstallBundler;
import org.apkplug.Bundle.installCallback;
import org.apkplug.app.FrameworkFactory;
import org.apkplug.app.FrameworkInstance;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

public class ProxyApplication extends Application {
    private static final String TAG = "ProxyApplication";

    private FrameworkInstance frame = null;

    public FrameworkInstance getFrame() {
        return frame;
    }

    public void onCreate() {
        super.onCreate();
        initApkPlug();

    }

    private void initApkPlug() {
        try {
            //启动框架
            frame = FrameworkFactory.getInstance().start(null, this);
            BundleContext context = frame.getSystemBundleContext();

            InstallBundler ib = new InstallBundler(context);
            ib.installForAssets("plugin_apk-debug-v1.0-b1.apk", "1.0", null, new installCallback() {
                        @Override
                        public void callback(int arg0, Bundle arg1) {
                            if (arg0 == installCallback.stutas5 || arg0 == installCallback.stutas7) {
                                Log.d(TAG, String.format("插件安装 %s ： %d", arg1.getName(), arg0));
                            } else {
                                Log.d(TAG, "插件安装失败 ：%s" + arg1.getName());
                            }
                        }
                    });

            registerHostService();
        } catch (Exception ex) {
            System.err.println("Could not create : " + ex);
            ex.printStackTrace();
            int nPid = android.os.Process.myPid();
            android.os.Process.killProcess(nPid);
        }
    }

    private void registerHostService() {
        final BundleContext context = frame.getSystemBundleContext();

        LoginManager loginManager = new LoginManagerImpl();

        context.registerService(LoginManager.class.getName(), loginManager, null);
    }

}
